#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stddef.h>

#include "StdFIFO.h"
#define true 1
#define false 0

struct StdFIFO
{
    char Name[FIFONAME_SIZE];
    int fd;
    OpenM mode;
};

FIFO* InitFIFO(const char *name)
{
    FIFO *f=(FIFO *)malloc(sizeof(FIFO));
    if(f==NULL)
    {
        printf("InitFIFO malloc error!\n");
        return NULL;
    }
    int ret = mkfifo(name,S_IRUSR|S_IWUSR);
    if(ret==-1)
    {
        printf("the FIFO is exist!\n");
    }
    strcpy(f->Name,name);
    return f;
}

int OpenFIFO(FIFO *f,OpenM mode)
{
    if(mode==ReadOnly)
    {
        f->fd=open(f->Name,O_RDONLY);
        if(f->fd==-1)
        {
            perror("openFIFO:");
            return false;
        }
    }
    else
    {
        f->fd=open(f->Name,O_WRONLY);
        if(f->fd==-1)
        {
            perror("openFIFO:");
            return false;
        }
    }  
    return true;
}

int ReadFromFIFO(FIFO *f, void *ptr,unsigned long size)
{
    if(f->mode==WriteOnly)
    {
        printf("FIFO mode is WriteOnly,cannot read!\n");
        return false;
    }
    if(read(f->fd,ptr,size)<=0)
    {
        perror("ReadFromFIFO");
        return false;
    }
    return true;
}

int WriteFormFIFO(FIFO *f, void *ptr, unsigned long size)
{
    if(f->mode==ReadOnly)
    {
        printf("FIFO mode is ReadOnly,cannot write!\n");
        return false;
    }
    if(write(f->fd,ptr,size)<=0)
    {
        perror("WriteFromFIFO");
        return false;
    }
    return true;
}

void FreeFIFO(FIFO *f)
{
    close(f->fd);
    char temp[100]={0};
    sprintf(temp,"rm -f %s",f->Name);
    system(temp);

    free(f);
}
